<template>
    <PageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="pageData.headerShow">
                <a-form size="mini" :model="pageData" layout="inline">
                    <a-form-item label="仓库类型">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="whChange" placeholder=""
                            v-model="searchData.whTypeName" allow-clear>
                            <a-option v-for="item in whTypeList" :value="item.typeName">
                                {{ item.typeName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="选择公司">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="companyChange" placeholder=""
                             v-model="searchData.firm" allow-clear>
                            <a-option v-for="item in companyList" :value="item.id">
                                {{ item.typeName ? item.typeName+ '-'+item.firmName : item.firmName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="仓库">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="searchData.wh" @click="ckisPd" @change="isWhilist" allow-clear>
                            <a-option v-for="item in whList" :value="item.id">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="单据类型">
                        <a-select popup-container="html"  class="bacClass" v-model="searchData.whType" allow-clear :style="{ width: '10rem' }">
                            <a-option :value="1">入库单</a-option>
                            <a-option :value="2">出库单</a-option>
                            <a-option :value="3">转仓单</a-option>
                            <a-option :value="4">退货单</a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="pageData.headerShow" @click="pageData.headerShow = false" :strokeWidth="2"
                        :size="18" />
                    <icon-double-down v-else @click="pageData.headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '审核', '驳回']" @select="selectHandler" @audit="audits" @rejected="rejecteds">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane title="单据审核">
                    <!-- <a-table :style="{
                        height: '100%'
                    }" size="mini" :scrollbar="true" sticky-header @page-change="pagination.change" stripe
                        :bordered="true" :columns="baseCol"
                        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                        v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                        :pagination="{ size: 'mini', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total }"
                        rowKey="orderNo">
                        <template #action="{ record }">
                            <a-space>
                                <a-button type="outline" status="success" size="mini"
                                    @click="isXiang(record)">
                                    <template #icon>
                                        <icon-find-replace />
                                    </template>
                                    详情
                                </a-button>
                                
                            </a-space>
                        </template>
                        <template #auditState="{ record }">
                            <a-button v-if="(record.auditState == 0)" type="primary" status="warning" size="mini"
                                disabled>待&nbsp;审&nbsp;核&nbsp;
                            </a-button>
                            <a-button v-if="(record.auditState == 2)" status="success" size="mini"
                                disabled>审核通过</a-button>
                            <a-button v-if="(record.auditState == 1)" type="primary" size="mini" status="danger"
                                disabled>审核驳回
                            </a-button>
                        </template>
                    </a-table> -->
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                        :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
                        :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                </a-tab-pane>
            </a-tabs>
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize"
            @page-size-change="change1" style="justify-content: center" :page-size="size" :current="page" />
        <!-- <a-drawer ok-text='保存' cancel-text='关闭' :style="{ 'zIndex': 999 }" :mask-closable="false" :height="600"
            :visible="pageData.showAdd" unmountOnClose @ok="sicksOk" placement="bottom" @cancel="sicksNo">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-space>
                    <a-button size="mini" type="primary" @click="tjWlzl">添加</a-button>
                </a-space>
                <div style="height:10px ;"></div>
                <a-table :style="{
                    height: '100%',
                    marginTop: '10px'
                }" stripe :bordered="true" :scrollbar="true" :pagination="false" sticky-header :columns="tableColumns"
                    :data="tableSjList">
                    <template v-for="(item, index) in tableColumns" #[item.slotName]="{ record }">
                        <a-input class="bacClass" v-if="(index != tableColumns.length - 1)" v-model="record[item.slotName]"></a-input>
                        <a-button v-else type="outline" size="mini" @click="deletWhsWl(record)">
                            <template #icon>
                                <icon-delete />
                            </template>
                            删除
                        </a-button>
                    </template>
                </a-table>
            </div>
        </a-drawer> -->
        <a-modal v-model:visible="visible" title="详情" :width="1200" :footer="false" :draggable="true">
            <a-table :style="{
                height: '500px',
                marginTop: '10px'
            }" stripe :bordered="true" :scrollbar="true" sticky-header :pagination="false" :columns="tableColumns1"
                :data="whListMingxs">
            </a-table>
        </a-modal>
    </PageTabelLayout>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, h, watch } from "vue";
import Toolbar from "@/components/Toolbar.vue";

import PageTabelLayout from "@/components/pageTabelLayout.vue";
import TreeUtils from "@/utils/TreeUtils";

import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { Message, Modal } from "@arco-design/web-vue";
import { tableColumns } from "@/components/processrowfactory/useTableList";
import { IconDoubleUp, IconDoubleDown, IconEdit, IconFindReplace, IconDelete } from "@arco-design/web-vue/es/icon";
import pagination from "@arco-design/web-vue/es/pagination";
import { table } from "console";
import { rowKey } from "element-plus/es/components/table-v2/src/common";

import {localeText} from '@/api/aggridZw'


export default {
    name: "OrderDeliveryList",

    setup() {

        const whService = new WHService()
        const whList = ref<any[]>([])
        const whTypeList = whService.whTypeList

        const whTypeFieldList = whService.whTypeFieldList
        const treeUtils = new TreeUtils()
        const companyList:any = whService.companyList
        const searchData = reactive<{
            whTypeName: string;
            firm: string,
            wh: string,
            whType: any
        }>({
            firm: '',
            whTypeName: "",
            wh: '',
            whType: ''
        });

        const baseCol: any[] = [{
            dataIndex: 'orderNo',
            key: 'orderNo',
            title: '单据编号',
            width: 180
        }, {
            dataIndex: 'firm',
            key: 'firm',
            title: '公司',
            width: 150
        }, {
            dataIndex: 'warehouseTypeName',
            key: 'warehouseTypeName',
            title: '仓库类型',
            width: 150
        },
        {
            dataIndex: 'warehouseName',
            key: 'warehouseName',
            title: '仓库',
            width: 150
        }
            , {
            dataIndex: 'auditName',
            key: 'auditName',
            title: '审核人',
            width: 100
        }, {
            title: '审核时间',
            dataIndex: 'auditTime',
            key: 'auditTime',
            width: 150
        },
        {
            title: '单据状态',
            dataIndex: 'infoState',
            key: 'infoState',
            width: 150
        },
        {
            title: '创建人',
            dataIndex: 'createName',
            key: 'createName',
            width: 150
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 180
        },
        {
            title: '修改人',
            dataIndex: 'updateName',
            key: 'updateName',
            width: 150
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 150
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            slotName: 'auditState',
            width: 100,
            key: 'auditState',
            fixed: "right",
        },
        {
            title: '详情',
            fixed: "right",
            slotName: 'action',
            width: 100
        }]

        const total = ref(10);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }

        function doRefresh() {
            pageData.pageLoading = true;
            post({
                url: "wms/WarehousetypeFieldvalue/getInvoicesByPage",
                data: {
                    "page": page.value,
                    "size": size.value,
                    "warehouseTypeName": searchData.whTypeName,
                    "firmId": searchData.firm,
                    "infoType": searchData.whType,
                    "warehouseId":searchData.wh
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false;
                });
        }



        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        let tableColumns: any = ref([])
        let tableColumns1: any = ref([])
        let tableListDatas = reactive({
            typeLesIds: 0
        })
        watch(() => whService.whTypeFieldList.value, () => {
            //  baseCol.splice(3,0, ...(whService.whTypeFieldList.value.map((f:any)=>{
            //     return {
            //         dataIndex:f.extendField,
            //         key:f.extendField,
            //         title:f.fieldName,
            //         width:150
            //     }
            // })))
            tableColumns.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                    ls: f.ls,
                    dropState: f.dropState,
                    conditions: f.conditions
                }
            })
            tableColumns1.value = whService.whTypeFieldList.value.map((f: any) => {
                return {
                    dataIndex: f.englishName,
                    key: f.englishName,
                    title: f.chineseName,
                    slotName: f.englishName,
                    width: 150,
                }
            })
            tableColumns1.value.unshift({
                dataIndex: 'orderNo',
                key: 'orderNo',
                title: '单据编号',
                width: 180
            }
            // , {
            //     dataIndex: 'firm',
            //     key: 'firm',
            //     title: '公司',
            //     width: 150
            // }, {
            //     dataIndex: 'warehouseTypeName',
            //     key: 'warehouseTypeName',
            //     title: '仓库类型',
            //     width: 150
            // },
            //     {
            //         dataIndex: 'warehouseName',
            //         key: 'warehouseName',
            //         title: '仓库',
            //         width: 150
            //     }
                )
            tableColumns.value.push(
                {
                    title: '操作',
                    fixed: "right",
                    slotName: 'action',
                    width: 150
                }
            )
            whService.whTypeFieldList.value.forEach((item: any) => {
                tableListDatas[item.englishName] = ''
            })


        })


        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            pageLoading: boolean
            headerShow: boolean

        }>({
            showAdd: false,
            sideTitle: "新增出库单",
            pageLoading: false,
            headerShow: true
        })

        // const addHandler = () => {
        //     if (searchData.whTypeName == '' || searchData.wh == '' || firm == ''||searchData.whType=='') {
        //         Message.error('请先选择主页仓库类型或选择公司或仓库和单据类型')
        //     } else {
        //         pageData.sideTitle = '新增出库单'
        //         pageData.showAdd = true
        //     }
        // }
        const selectHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '' || searchData.whType == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库和单据类型')
            } else {
                page.value = 1
                doRefresh()
            }
        }
        const whChange = () => {
            whList.value = []
            searchData.wh = ''
            searchData.firm = ''
        }
        watch(() => whService.whList.value, (o, n) => {


            whList.value = whService.whList.value
        })
        // 公司下拉框 改变
        const companyChange = (val: any) => {
            whList.value = []
            searchData.wh = ''
            whService.getWarhouseList(searchData.firm, searchData.whTypeName)
        }

        let visible = ref(false)
        let whListMingxs = ref<any[]>([])
        const isXiang = async (val: any) => {
            const res: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firmId)
            if (res.code == 200) {
                whListMingxs.value = res.data
                visible.value = true
            }
        }
        let tableSjList: any = ref([])
        const tjWlzl = () => {
            tableListDatas.typeLesIds++
            tableSjList.value.push(JSON.parse(JSON.stringify(tableListDatas)))
        }
        const sicksOk = async () => {
            tableListDatas.typeLesIds = 0
            if (pageData.sideTitle == '新增出库单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 2
                })
                const res: any = await whService.addWarhouseMinxList(tableSjList.value)
                if (res.code == 200) {
                    tableSjList.value = []
                    doRefresh()
                    Message.success('添加成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            } else if (pageData.sideTitle == '修改出库单') {
                tableSjList.value.forEach((item: any) => {
                    item['warehouseTypeName'] = searchData.whTypeName
                    item['warehouseName'] = searchData.wh
                    item['firm'] = searchData.firm
                    item['infoType'] = 2
                    item['orderNo'] = orderNos
                    item['createName'] = tableSjList.value[0].createName
                    item['createTime'] = tableSjList.value[0].createTime
                })
                let updataWhdataList = {
                    warehouseTypeName: searchData.whTypeName,
                    warehouseName: searchData.wh,
                    firm: searchData.firm,
                    updateInfo: tableSjList.value
                }
                const res: any = await whService.updataWarhouseMinxList(updataWhdataList)
                if (res.code == 200) {
                    orderNos = ''
                    tableSjList.value = []
                    doRefresh()
                    Message.success('修改成功')
                    pageData.showAdd = false
                } else {
                    Message.error(res.message)
                }
            }
        }
        const sicksNo = () => {
            tableListDatas.typeLesIds = 0
            tableSjList.value = []
            pageData.showAdd = false
        }
        let orderNos: any;
        const xingXg = async (val: any) => {
            orderNos = val.orderNo
            const res = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
            if (res.code == 200) {
                tableSjList.value = res.data
                pageData.sideTitle = '修改出库单'
                pageData.showAdd = true
            }
        }

        const deletWh = (val: any) => {
            let objDelet = {
                warehouseTypeName: val.warehouseTypeName,
                warehouseName: val.warehouseName,
                firm: val.firm,
                delOrderNoInfo: [val.orderNo]
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk: async () => {
                    const res: any = await whService.deletWarhouseMinxList(objDelet)
                    if (res.code == 200) {
                        Message.success('删除成功')
                        doRefresh()
                    } else {
                        Message.error(res.message)
                    }
                }
            })
        }
        const deletWhsWl = (val: any) => {
            let objDelet = {
                warehouseTypeName: val.warehouseTypeName,
                warehouseName: val.warehouseName,
                firm: val.firm,
                delInfo: [val.id]
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk: async () => {
                    if (val.id == undefined) {
                        tableSjList.value.forEach((item: any, index: any) => {
                            if (val.typeLesIds == item.typeLesIds) {
                                tableSjList.value.splice(index, 1)
                            }
                        })
                        if (tableSjList.value.length == 0) {
                            pageData.showAdd = false
                        }
                    } else {
                        const res: any = await whService.deletWhmxWarhouseMinxList(objDelet)
                        if (res.code == 200) {
                            Message.success('删除成功')
                            const resz: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firm)
                            if (resz.code == 200) {
                                if (resz.data.length == 0) {
                                    whListMingxs.value = resz.data
                                    tableSjList.value = resz.data
                                    doRefresh()
                                    pageData.showAdd = false
                                } else {
                                    whListMingxs.value = resz.data
                                    tableSjList.value = resz.data
                                }
                            }
                        } else {
                            Message.error(res.message)
                        }
                    }
                }
            })
        }
        const audits = () => {
            if (gridOption.value.getSelectedRows().length == 0) {
                Message.error('请勾选数据')
                return
            }
            let isDatasList:any = []
            gridOption.value.getSelectedRows().forEach((item: any) => {
                table.dataList.forEach((items: any) => {
                    if (item.orderNo == items.orderNo) {
                        isDatasList.push(
                            {
                                "warehouseTypeName": items.warehouseTypeName,
                                "warehouseName": items.warehouseName,
                                "firm": items.firm,
                                "firmId": items.firmId,
                                "warehouseId":items.warehouseId,
                                "orderNo": items.orderNo,
                                "auditState": 2
                            }
                        )
                    }
                })
            })
            Modal.confirm({
                title: '系统提示',
                content: '单据审核!',
                onOk:async ()=>{
                   const res:any = await whService.auditsWhmxWarhouse(isDatasList)
                   if(res.code ==200){
                       doRefresh()
                       selectedRowKeys.value = []
                       Message.success('审核通过')
                   }else{
                       Message.error(res.message)
                   }
                }
            })
        }
        const rejecteds = () => {
            if (gridOption.value.getSelectedRows().length == 0) {
                Message.error('请勾选数据')
                return
            }
            let isDatasList:any = []
            gridOption.value.getSelectedRows().forEach((item: any) => {
                table.dataList.forEach((items: any) => {
                    if (item.orderNo == items.orderNo) {
                        isDatasList.push(
                            {
                                "warehouseTypeName": items.warehouseTypeName,
                                "warehouseName": items.warehouseName,
                                "firm": items.firm,
                                "firmId": items.firmId,
                                "warehouseId":items.warehouseId,
                                "orderNo": items.orderNo,
                                "auditState": 1
                            }
                        )
                    }
                })
            })
            Modal.confirm({
                title: '系统提示',
                content: '单据驳回!',
                onOk:async ()=>{
                   const res:any = await whService.auditsWhmxWarhouse(isDatasList)
                   if(res.code ==200){
                       doRefresh()
                       selectedRowKeys.value = []
                       Message.success('审核通过')
                   }else{
                       Message.error(res.message)
                   }
                }
            })
        }
        const ckisPd = ()=>{
            if(searchData.whTypeName =='' ||searchData.firm==''){
                Message.error('请先选择仓库类型和所属工厂')
                return
            }
        }

        const isWhilist = (whName:any)=>{
            whService.loadWHTypeFieldList({warehouseId:whName,showType:1})
        }
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
        }
        let tc: any[] = baseCol.map((o: any) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed'],
                width: 150
            }
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 150
                obj['cellRenderer'] = {
                    template: `
                    <a-space>
                                <a-button type="outline" status="success" size="mini"
                                    @click="a1">
                                    <template #icon>
                                        <icon-find-replace />
                                    </template>
                                    详情
                                </a-button>
                                
                            </a-space>
                    `,
                    setup(props: any) {
                        const a1 = () => {
                            isXiang(props.params.data)
                        }
                        return {
                            a1,
                        }
                    }
                }
            }
            if (o.slotName === 'auditState') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 120
                obj['cellRenderer'] = {
                    template: `<a-button v-if="(isDatas.auditState == 0)" type="primary" status="warning" size="mini"
                                disabled>待&nbsp;审&nbsp;核&nbsp;
                            </a-button>
                            <a-button v-if="(isDatas.auditState == 2)" status="success" size="mini"
                                disabled>审核通过</a-button>
                            <a-button v-if="(isDatas.auditState == 1)" type="primary" size="mini" status="danger"
                                disabled>审核驳回
                            </a-button>`,
                    setup(props: any) {
                        const isDatas = ref(props.params.data)
                        return {
                            isDatas
                        }
                    }
                }
            }
            if (o.slotName === 'infoState') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 100
                obj['cellRenderer'] = {
                    template: `
                            <a-button v-if="(isDatas.infoState == 0)" status="success" size="mini" disabled>待入库
                            </a-button>
                            <a-button v-if="(isDatas.infoState == 1)" type="primary" size="mini" status="danger"
                                disabled>已入库
                            </a-button>`,
                    setup(props: any) {
                        const isDatas = ref(props.params.data)
                        return {
                            isDatas
                        }
                    }
                }
            }
            return obj
        })

        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)
        const localeText1:any=ref(localeText)
        return {
            localeText1,
            change1,
            PageSize,
            total,
            page,
            size,
            tc,
            defaultColDef,
            gridReady,
            gridOption,
            isWhilist,
            ckisPd,
            rejecteds,
            audits,
            tableColumns1,
            deletWhsWl,
            deletWh,
            xingXg,
            sicksNo,
            sicksOk,
            tableSjList,
            tableListDatas,
            tjWlzl,
            whListMingxs,
            isXiang,
            visible,
            companyChange,
            whChange,
            selectHandler,
            // addHandler,
            companyList,
            whList,
            whTypeList,
            selectedRowKeys,
            whTypeFieldList,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            searchData,
            baseCol
        };
    },
    components: { PageTabelLayout , }
};
</script>
<style scoped lang="less">

</style>
